#include "UrlEncode2.h"

bool includeChar(char c)
{
  bool b1 = isAlphaNumeric(c);
  bool b2 = c == '-' || c == '_' || c == '.' || c == '~';
  return b1 || b2;
}

char* urlEncode(char *msg, int resultLength)
{
  int index = 0;
  int outputIndex = 0;
  char encodedMsg [resultLength];
  const char *hex = "0123456789ABCDEF";

  while (msg[index] != '\0')
  {
    if (includeChar(msg[index]))
    {
      encodedMsg[outputIndex] = msg[index];
      index += 1;
      outputIndex += 1;
    }
    else
    {
      encodedMsg[outputIndex] = '%';
      encodedMsg[outputIndex + 1] = hex[(unsigned char)msg[index] >> 4];
      encodedMsg[outputIndex + 2] = hex[msg[index] & 0xf];
      index += 1;
      outputIndex += 3;
    }
  }

  char *result = encodedMsg;
  return result;
}
